package cleancode.view;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import cleancode.controller.commandexecutor.CommandExecutor;
import cleancode.controller.commandexecutor.CommandHandler;
import cleancode.datasource.DataSourceHandler;
import cleancode.datasource.DataSourceHandlerFactory;
import cleancode.model.PersistentData;

/**
 * CMD user managerment demo, you can enter commands and manage the users, roles and operations.
 */
public class CMDUserManagermentSystem
{
    private PersistentData persistentData = new PersistentData();

    private CommandHandler commandHandler;

    private DataSourceHandler dataSourceHandler;

    public CMDUserManagermentSystem()
    {
        this( null );
    }

    public CMDUserManagermentSystem( Object dataSource )
    {
        if( dataSource != null )
        {
            dataSourceHandler = DataSourceHandlerFactory.createDataSourceHandler( dataSource );
            if( dataSourceHandler != null )
            {
                try
                {
                    dataSourceHandler.load( persistentData );
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                    System.exit( 1 );
                }
            }
        }
        commandHandler = new CommandExecutor( persistentData );
    }

    public void start()
    {
        System.out.println( "Welcome to the system! Please enter user name to login. Enter 'q' to quit." );
        System.out.println( commandHandler.help() );
        BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
        String command = null;
        try
        {
            while( ( command = reader.readLine() ) != null && !"q".equals( command ) )
            {
                System.out.println( commandHandler.handleCommand( command.trim() ) );
            }
            System.out.println( "Bye!" );
        }
        catch( IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if( dataSourceHandler != null )
                {
                    dataSourceHandler.save( persistentData );
                }
                reader.close();
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }
    }

}
